package top.lingkang.finaloauth2.server.client.impl;

import cn.hutool.core.collection.CollUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import top.lingkang.finaloauth2.server.client.ClientDetails;
import top.lingkang.finaloauth2.server.client.ClientDetailsService;
import top.lingkang.finaloauth2.utils.StringUtils;

import javax.sql.DataSource;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashSet;
import java.util.List;

/**
 * @author lingkang
 * Created by 2022/3/24
 */
public class JdbcClientDetailsService implements ClientDetailsService {
    private static final Log log = LogFactory.getLog(JdbcClientDetailsService.class);
    private final JdbcTemplate template;

    public JdbcClientDetailsService(DataSource dataSource) {
        template = new JdbcTemplate(dataSource);
        log.info("server: 使用jdbc读取授权客户端，ok");
    }

    @Override
    public ClientDetails loadClientByClientId(String clientId) {
        List<ClientDetails> query = template.query(
                "select client_id,client_secret,`scope`,grant_type from fo_client where client_id=?",
                new String[]{clientId},
                new RowMapper<ClientDetails>() {
                    @Override
                    public ClientDetails mapRow(ResultSet resultSet, int i) throws SQLException {
                        ClientDetails details = new ClientDetails();
                        details.setClientId(resultSet.getString("client_id"));
                        details.setClientSecret(resultSet.getString("client_secret"));
                        details.setScope(resultSet.getString("scope"));
                        String type = resultSet.getString("grant_type");
                        if (!StringUtils.isEmpty(type)) {
                            String[] split = type.replaceAll(" ", "").split(",");
                            HashSet<String> grant = new HashSet<>();
                            for (String s : split) {
                                if (StringUtils.isEmpty(s))
                                    continue;
                                grant.add(s);
                            }
                            details.setGrantType(grant);
                        }
                        return details;
                    }
                });
        if (CollUtil.isEmpty(query)) {
            return null;
        }
        return query.get(0);
    }

}
